package com.kexun.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/test")
public class OneServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String method = request.getParameter("method");
        System.out.println(method);
 /*       if (method.equals("doSel")) {
            doSel(request, response);
        } else if (method.equals("doIns")) {
            doIns(request, response);
        } else if (method.equals("doUpd")) {
            doUpd(request, response);
        } else {
            doDel(request, response);
        }*/
        // 2 改进
        try {
            //暴力反射获取当前类中的方法（ 请求参数 == 方法名 ）
            Method m = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法时，如果方法的修饰权限protected，需要解除权限
            m.setAccessible(true);
            m.invoke(this,request,response);
        } catch (Exception e) {
            throw new RuntimeException("请求有误，找不到具体的方法处理请求");
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    // 处理查询
    protected void doSel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //调用业务逻辑
        //处理
        //分发
        response.getWriter().print("执行了查询");
    }

    protected void doIns(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("执行了添加");
    }

    protected void doUpd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("执行了修改");
    }

    protected void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().print("执行了删除");
    }


}
